package com.jsaas.sys.controller;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jsaas.controller.base.BaseController;
import com.jsaas.core.qparams.PageQueryParams;
import com.jsaas.model.Role;
import com.jsaas.model.User;
import com.jsaas.sys.service.UserRoleService;
import com.jsaas.sys.service.UserService;

/**   
* @Title: UserController.java 
* @Package com.jsaas.sys.controller 
* @Description: TODO(用一句话描述该文件做什么) 
* @author tuozq 
* @date 2017年11月6日 上午9:37:06 
* @version V1.0   
*/
public class UserController extends BaseController {
	
	public void index(){
		render("listUser.html");
	}
	
	public void edit(){
		String id = getPara("id");
		if(StrKit.isBlank(id)){
			setAttr("user", new User());
		}else{
			setAttr("user", User.dao.findById(id));
		}
		render("editUser.html");
	}
	
	/**
	 * 注册账号
	 */
	@Before(Tx.class)
	public void save(){
		User user = getModel(User.class, "user");
		Ret ret = enhance(UserService.class).save(user);
		renderJson(ret);
	}
	
	public void query(){
		PageQueryParams params = initPageParams(getRequest(), "user.findUser");
		Page<User> pagedata = User.dao.pageinit(params);
		renderJson(pagedata);
	}
	
	@Before(Tx.class)
	public void delete(){
		String id = getPara("id");
		if(StrKit.notBlank(id)){
			User.dao.deleteById(id);
			//删除用户绑定的角色关系
			Duang.duang(UserRoleService.class).deleteByUserId(id);
			renderJson(Ret.ok());
		}else{
			renderJson(Ret.fail("msg", "用户ID不能为空。"));
		}
	}
	
	/**
	 * 编辑用户角色
	 */
	@Before(Tx.class)
	public void editUserRole(){
		String userId = getPara("userId");
		SqlPara sqlPara = Db.getSqlPara("user.findUserRoleByUserId", Kv.by("userId", userId));
		List<Role> allRoles = Role.dao.find(sqlPara);
		List<Kv> list = new ArrayList<Kv>();
		for (Role role : allRoles) {
			list.add(Kv.by("id", role.getId()).set("desc", role.getRoleName()).set("checked", StrKit.notBlank(role.getStr("userroleid"))));
		}
		setAttr("userId", userId);
		setAttr("roles", list);
		render("editUserRole.html");
	}
	
	/**
	 * 保存用户与角色关系
	 */
	@Before(Tx.class)
	public void saveUserRole(){
		String userId = getPara("userId");
		String roleIds = getPara("roleIds");
		Ret ret = Duang.duang(UserRoleService.class).save(userId, roleIds);
		renderJson(ret);
	}

}
